import { ref } from 'vue'
import { useInterviewQuestionsSearchFormState } from './useInterviewQuestionsSearchFormState'
import type InterviewQuestionsForm from '../InterviewQuestionsForm.vue'
import { notification, message } from 'ant-design-vue'
import { edit, view } from '@/apis/InterviewQuestions'
import type { InterviewQuestionsEdit } from '@/models/InterviewQuestions/InterviewQuestionsEdit'

export function useInterviewQuestionsEdit(entityName: string, searchFunc: () => void) {
  const editModal = ref(false)
  const editLoading = ref(false)
  const editFormRef = ref<null | InstanceType<typeof InterviewQuestionsForm>>()
  const { formState, resetFormState, setFormState } = useInterviewQuestionsSearchFormState()

  async function onEdit(id?: number) {
    if (!id) return
    editModal.value = true
    editLoading.value = true
    try {
      const res = await view(id)
      if (res.data) {
        setFormState({
          ...res.data,
          id,
        })
        editFormRef.value?.setFormStata({ ...formState })
      }
    } catch (error) {}
    editLoading.value = false
  }

  async function onEditOk() {
    const formData = await editFormRef.value?.getFormState()
    if (editLoading.value) return
    if (!formData) return
    setFormState({ ...formData, id: formState.id })
    if (!formState.id) return
    editLoading.value = true
    try {
      const res = await edit({
        ...formState,
      } as InterviewQuestionsEdit)
      if (res.data) {
        message.success(`修改${entityName}成功!`)
        editLoading.value = false
        searchFunc()
        onEditCancel()
        return
      } else {
        notification.error({ message: `修改${entityName}失败!` })
      }
    } catch (error) {
      notification.error({
        message: `修改${entityName}失败!`,
      })
    }
    editLoading.value = false
    onEditCancel()
  }
  function onEditCancel() {
    resetFormState()
    editFormRef.value?.resetFormStata()
    editModal.value = false
  }

  return { editModal, editLoading, editFormRef, onEdit, onEditOk, onEditCancel }
}
